/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.websockets;

import com.entities.EventTypeCharts;
import com.model.ChartData;
import java.io.StringReader;
import java.util.List;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 *
 * @author Tuan Long
 */
@ServerEndpoint("/adminendpoint")
public class AdminWSEndpoint {

    @Inject
    private AdminSessionHandler sessionHandler;
    
    @OnMessage
    public void onMessage(String message, Session session) {
        try (JsonReader reader = Json.createReader(new StringReader(message))) {
            JsonObject jsonMessage = reader.readObject();
            if ("listen".equals(jsonMessage.getString("action"))) {
                List<EventTypeCharts> data = ChartData.getEventTotalTypeData();
                ChartDataManager manager = new ChartDataManager();
                manager.setData(data);
                if(data != null){
                    sessionHandler.addChart(manager);
                }
            }
        }
    }
    @OnOpen
    public void onOpen(Session session) {
        sessionHandler.addSession(session);
    }

    @OnClose
    public void onClose(Session session) {
        sessionHandler.removeSession(session);
    }

    @OnError
    public void onError(Throwable t) {
        t.printStackTrace();
    }
}
